package org.zkdemo.test;

import java.io.Closeable;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import org.springframework.scheduling.annotation.Async;

public class ZookeeperFactory implements Closeable
{
    private ZooKeeperServerMain keeperServerMain;
    private static final Logger LOGGER = Logger.getLogger(ZookeeperFactory.class);
    
    public ZookeeperFactory()
    {
        
    }
    
    @Async
    public void init() throws Exception
    {
        if (keeperServerMain == null)
        {
            Properties startupProperties = new Properties();
            
            startupProperties.put("tickTime", 2000);
            startupProperties.put("initLimit", 10);
            startupProperties.put("syncLimit", 5);
            startupProperties.put("clientPort", 2181);
            startupProperties.put("dataDir", "d:/temp");
            
            QuorumPeerConfig quorumConfiguration = new QuorumPeerConfig();
            quorumConfiguration.parseProperties(startupProperties);
            
            keeperServerMain = new ZooKeeperServerMain();
            final ServerConfig configuration = new ServerConfig();
            configuration.readFrom(quorumConfiguration);
            
            LOGGER.info("Starting zookeeper ...");
            keeperServerMain.runFromConfig(configuration);
        }
        
    }
    
    @Override
    public void close() throws IOException
    {
        LOGGER.info("Closing zookeeper server ....");
    }
    
}
